// pages/combined-detect/combined-detect.js
const app = getApp()

Page({
  data: {
    // 检测步骤
    detectionSteps: [
      { id: 'camera', name: '镜头检测', icon: '📷', status: 'pending' },
      { id: 'wifi', name: 'WiFi扫描', icon: '📡', status: 'pending' },
      { id: 'magnetic', name: '磁场检测', icon: '🧭', status: 'pending' },
      { id: 'bluetooth', name: '蓝牙扫描', icon: '📱', status: 'pending' }
    ],
    currentStep: 0,
    totalSteps: 4,
    
    // 当前检测
    currentDetection: {
      id: '',
      name: '',
      desc: '',
      icon: '',
      status: 'pending',
      completed: false,
      riskLevel: 'low',
      resultIcon: '',
      resultTitle: '',
      resultDesc: ''
    },
    
    // 检测状态
    isDetecting: false,
    allCompleted: false,
    detectionStartTime: null,
    detectionDuration: '00:00',
    
    // 各检测结果
    cameraResult: {
      suspiciousPoints: [],
      riskLevel: 'low',
      riskText: '低风险'
    },
    wifiResult: {
      totalDevices: 0,
      suspiciousDevices: [],
      riskLevel: 'low',
      riskText: '低风险'
    },
    magneticResult: {
      currentValue: 0,
      change: 0,
      anomalies: [],
      riskLevel: 'low',
      riskText: '低风险'
    },
    
    // 综合结果
    overallRisk: {
      level: 'low',
      text: '低风险',
      score: 0,
      confidence: 85
    },
    
    // 相机相关
    showCamera: false,
    flashMode: 'off',
    
    // WiFi相关
    wifiScanning: false,
    
    // 风险等级映射
    riskLevelMap: {
      low: '低风险',
      medium: '中风险',
      high: '高风险'
    }
  },

  onLoad() {
    console.log('综合检测页面加载')
    this.initDetectionSteps()
  },

  onShow() {
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
  },

  onHide() {
    this.stopDetection()
  },

  onUnload() {
    this.cleanup()
  },

  // 清理资源
  cleanup() {
    this.stopDetection()
    wx.setKeepScreenOn({
      keepScreenOn: false
    })
    this.clearTimers()
  },

  // 清理定时器
  clearTimers() {
    if (this.detectionTimer) {
      clearInterval(this.detectionTimer)
      this.detectionTimer = null
    }
    if (this.durationTimer) {
      clearInterval(this.durationTimer)
      this.durationTimer = null
    }
  },

  // 初始化检测步骤
  initDetectionSteps() {
    const steps = this.data.detectionSteps.map(step => ({
      ...step,
      status: 'pending'
    }))
    
    this.setData({
      detectionSteps: steps,
      currentStep: 0,
      allCompleted: false,
      isDetecting: false
    })
    
    this.updateCurrentDetection()
  },

  // 更新当前检测信息
  updateCurrentDetection() {
    const currentStepIndex = this.data.currentStep
    const step = this.data.detectionSteps[currentStepIndex]
    
    if (!step) return
    
    const detectionInfo = {
      camera: {
        name: '镜头反光检测',
        desc: '使用闪光灯检测可疑反光点',
        icon: '📷'
      },
      wifi: {
        name: 'WiFi网络扫描',
        desc: '扫描环境中的可疑设备',
        icon: '📡'
      },
      magnetic: {
        name: '磁场感应检测',
        desc: '检测磁场异常变化',
        icon: '🧭'
      }
    }
    
    const info = detectionInfo[step.id] || {}
    
    this.setData({
      currentDetection: {
        id: step.id,
        name: info.name || step.name,
        desc: info.desc || '',
        icon: info.icon || step.icon,
        status: step.status,
        completed: step.status === 'completed'
      }
    })
  },

  // 开始检测
  startDetection() {
    // 检查权限
    this.checkPermissions().then(() => {
      this.setData({
        isDetecting: true,
        detectionStartTime: Date.now(),
        currentStep: 0
      })
      
      // 开始计时
      this.startDurationTimer()
      
      // 开始第一个检测
      this.startCurrentDetection()
      
      wx.showToast({
        title: '开始综合检测',
        icon: 'success'
      })
    }).catch((error) => {
      wx.showModal({
        title: '权限不足',
        content: error,
        showCancel: false
      })
    })
  },

  // 检查权限
  checkPermissions() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: (res) => {
          const missingPermissions = []
          
          if (res.authSetting['scope.camera'] === false) {
            missingPermissions.push('相机权限')
          }
          
          if (missingPermissions.length > 0) {
            reject(`缺少必要权限: ${missingPermissions.join('、')}`)
          } else {
            resolve()
          }
        },
        fail: () => {
          reject('权限检查失败')
        }
      })
    })
  },

  // 开始计时
  startDurationTimer() {
    this.durationTimer = setInterval(() => {
      if (!this.data.detectionStartTime) return
      
      const elapsed = Date.now() - this.data.detectionStartTime
      const minutes = Math.floor(elapsed / 60000)
      const seconds = Math.floor((elapsed % 60000) / 1000)
      
      this.setData({
        detectionDuration: `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
      })
    }, 1000)
  },

  // 开始当前检测
  startCurrentDetection() {
    const currentStepIndex = this.data.currentStep
    const steps = [...this.data.detectionSteps]
    
    if (currentStepIndex >= steps.length) {
      this.completeAllDetections()
      return
    }
    
    // 更新步骤状态
    steps[currentStepIndex].status = 'active'
    this.setData({ detectionSteps: steps })
    this.updateCurrentDetection()
    
    const currentStep = steps[currentStepIndex]
    
    switch (currentStep.id) {
      case 'camera':
        this.startCameraDetection()
        break
      case 'wifi':
        this.startWifiDetection()
        break
      case 'magnetic':
        this.startMagneticDetection()
        break
    }
  },

  // 镜头检测
  startCameraDetection() {
    this.setData({
      showCamera: true,
      flashMode: 'torch'
    })
    
    // 实际应用中这里应该集成真实的图像处理逻辑
    wx.showModal({
      title: '镜头检测',
      content: '请使用闪光灯扫描可疑区域，检测完成后手动进入下一步',
      showCancel: false,
      success: () => {
        // 10秒后自动进入下一步
        setTimeout(() => {
          this.completeCameraDetection()
        }, 10000)
      }
    })
  },

  // 完成镜头检测
  completeCameraDetection() {
    const suspiciousCount = this.data.cameraResult.suspiciousPoints.length
    let riskLevel = 'low'
    let riskText = '低风险'
    
    if (suspiciousCount >= 3) {
      riskLevel = 'high'
      riskText = '高风险'
    } else if (suspiciousCount >= 1) {
      riskLevel = 'medium'
      riskText = '中风险'
    }
    
    this.setData({
      'cameraResult.riskLevel': riskLevel,
      'cameraResult.riskText': riskText,
      showCamera: false,
      flashMode: 'off'
    })
    
    this.completeCurrentStep()
  },

  // WiFi检测
  startWifiDetection() {
    this.setData({
      wifiScanning: true
    })
    
    wx.showModal({
      title: 'WiFi扫描',
      content: '请确保已开启位置权限，正在扫描网络设备...',
      showCancel: false,
      success: () => {
        // 5秒后自动进入下一步
        setTimeout(() => {
          this.setData({
            wifiScanning: false
          })
          this.completeCurrentStep()
        }, 5000)
      }
    })
  },

  // 磁场检测
  startMagneticDetection() {
    wx.showModal({
      title: '磁场检测',
      content: '请移动手机靠近可疑位置，观察磁场变化...',
      showCancel: false,
      success: () => {
        // 8秒后自动进入下一步
        setTimeout(() => {
          this.completeMagneticDetection()
        }, 8000)
      }
    })
  },

  // 完成磁场检测
  completeMagneticDetection() {
    const anomaliesCount = this.data.magneticResult.anomalies.length
    let riskLevel = 'low'
    let riskText = '低风险'
    
    if (anomaliesCount >= 3) {
      riskLevel = 'high'
      riskText = '高风险'
    } else if (anomaliesCount >= 1) {
      riskLevel = 'medium'
      riskText = '中风险'
    }
    
    this.setData({
      'magneticResult.riskLevel': riskLevel,
      'magneticResult.riskText': riskText
    })
    
    this.completeCurrentStep()
  },

  // 完成当前步骤
  completeCurrentStep() {
    const steps = [...this.data.detectionSteps]
    const currentStepIndex = this.data.currentStep
    
    steps[currentStepIndex].status = 'completed'
    
    this.setData({
      detectionSteps: steps,
      currentStep: currentStepIndex + 1
    })
    
    // 延迟一下再进行下一步
    setTimeout(() => {
      if (currentStepIndex + 1 < this.data.totalSteps) {
        this.startCurrentDetection()
      } else {
        this.completeAllDetections()
      }
    }, 1500)
  },

  // 完成所有检测
  completeAllDetections() {
    this.setData({
      isDetecting: false,
      allCompleted: true
    })
    
    this.clearTimers()
    this.calculateOverallRisk()
    
    wx.showToast({
      title: '检测完成',
      icon: 'success'
    })
  },

  // 计算综合风险
  calculateOverallRisk() {
    const { cameraResult, wifiResult, magneticResult } = this.data
    
    // 计算风险分数
    let totalScore = 0
    let maxScore = 0
    
    // 镜头检测评分
    const cameraScore = Math.min(cameraResult.suspiciousPoints.length * 30, 100)
    totalScore += cameraScore
    maxScore += 100
    
    // WiFi检测评分
    const wifiScore = Math.min(wifiResult.suspiciousDevices.length * 40, 100)
    totalScore += wifiScore
    maxScore += 100
    
    // 磁场检测评分
    const magneticScore = Math.min(magneticResult.anomalies.length * 25, 100)
    totalScore += magneticScore
    maxScore += 100
    
    const finalScore = Math.round((totalScore / maxScore) * 100)
    
    // 确定风险等级
    let riskLevel = 'low'
    let riskText = '低风险'
    
    if (finalScore >= 70) {
      riskLevel = 'high'
      riskText = '高风险'
    } else if (finalScore >= 40) {
      riskLevel = 'medium'
      riskText = '中风险'
    }
    
    // 计算可信度
    const hasMultiplePositives = [
      cameraResult.riskLevel !== 'low',
      wifiResult.riskLevel !== 'low',
      magneticResult.riskLevel !== 'low'
    ].filter(Boolean).length
    
    const confidence = Math.min(85 + hasMultiplePositives * 5, 95)
    
    this.setData({
      overallRisk: {
        level: riskLevel,
        text: riskText,
        score: finalScore,
        confidence: confidence
      }
    })
  },

  // 暂停检测
  pauseDetection() {
    wx.showModal({
      title: '暂停检测',
      content: '确定要暂停当前检测吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            isDetecting: false
          })
          this.clearTimers()
          wx.showToast({
            title: '检测已暂停',
            icon: 'none'
          })
        }
      }
    })
  },

  // 停止检测
  stopDetection() {
    wx.showModal({
      title: '停止检测',
      content: '确定要停止检测吗？已完成的步骤结果将保留。',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            isDetecting: false
          })
          this.clearTimers()
          this.calculateOverallRisk()
          wx.showToast({
            title: '检测已停止',
            icon: 'none'
          })
        }
      }
    })
  },

  // 重新开始检测
  restartDetection() {
    wx.showModal({
      title: '重新检测',
      content: '确定要重新开始检测吗？当前结果将被清除。',
      success: (res) => {
        if (res.confirm) {
          this.initDetectionSteps()
          this.resetResults()
        }
      }
    })
  },

  // 重置结果
  resetResults() {
    this.setData({
      cameraResult: {
        suspiciousPoints: [],
        riskLevel: 'low',
        riskText: '低风险'
      },
      wifiResult: {
        totalDevices: 0,
        suspiciousDevices: [],
        riskLevel: 'low',
        riskText: '低风险'
      },
      magneticResult: {
        currentValue: 0,
        change: 0,
        anomalies: [],
        riskLevel: 'low',
        riskText: '低风险'
      },
      overallRisk: {
        level: 'low',
        text: '低风险',
        score: 0,
        confidence: 85
      },
      detectionDuration: '00:00'
    })
  },

  // 查看结果
  viewResults() {
    // 这里可以显示详细的结果页面或弹窗
    wx.showModal({
      title: '检测结果详情',
      content: `镜头检测: ${this.data.cameraResult.suspiciousPoints.length}个可疑点\nWiFi扫描: ${this.data.wifiResult.suspiciousDevices.length}个可疑设备\n磁场检测: ${this.data.magneticResult.anomalies.length}个异常点\n\n综合风险: ${this.data.overallRisk.text}`,
      showCancel: false
    })
  },

  // 保存结果
  saveResults() {
    const result = {
      id: app.utils.generateId(),
      timestamp: Date.now(),
      location: '',
      detectType: 'combined',
      result: {
        camera: {
          suspiciousPoints: this.data.cameraResult.suspiciousPoints,
          photos: []
        },
        wifi: {
          totalDevices: this.data.wifiResult.totalDevices,
          suspiciousDevices: this.data.wifiResult.suspiciousDevices
        },
        magnetic: {
          baseline: 45, // 模拟基准值
          anomalies: this.data.magneticResult.anomalies
        }
      },
      riskLevel: this.data.overallRisk.level,
      overallScore: this.data.overallRisk.score,
      confidence: this.data.overallRisk.confidence,
      notes: ''
    }

    // 保存到本地存储
    const history = wx.getStorageSync('detection_history') || []
    history.unshift(result)
    wx.setStorageSync('detection_history', history)

    wx.showModal({
      title: '保存成功',
      content: `综合检测结果已保存\n风险等级: ${this.data.overallRisk.text}\n综合评分: ${this.data.overallRisk.score}分`,
      showCancel: false,
      success: () => {
        wx.showModal({
          title: '查看历史',
          content: '是否跳转到历史记录页面查看详情？',
          success: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/history/history'
              })
            }
          }
        })
      }
    })
  },

  // 分享给好友
  onShareAppMessage() {
    const { overallRisk, allCompleted } = this.data
    
    return {
      title: allCompleted ? 
        `综合检测完成，风险等级: ${overallRisk.text} - 安心住助手` : 
        '多维度综合检测工具 - 安心住助手',
      desc: '镜头、WiFi、磁场、蓝牙四种检测方式综合分析',
      path: '/pages/combined-detect/combined-detect'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '综合检测 - 安心住助手',
      query: 'tool=combined'
    }
  }
})
